package com.newly.center.sys.service.auth.impl;

import cn.hutool.core.util.ObjectUtil;
import com.newly.common.base.constants.AuthConstant;
import com.newly.common.base.entity.auth.AuthPayload;
import com.newly.common.base.entity.auth.ICurrentTenant;
import com.newly.common.base.entity.auth.TenantDetails;
import com.newly.common.core.utils.RequestUtils;
import com.newly.transfer.redis.RedisTransfer;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @program: newly-parent
 * @remark: 权限业务基类
 * @author: guan
 * @create: 2021-12-23 05:32
 */
public class AbstractAuthService {

    protected static final int ADD = 1;

    protected static final int DEL = 0;

    @Autowired
    protected RedisTransfer redisTransfer;

    @Autowired
    protected RequestUtils requestUtils;

    protected boolean handleAuthPayloads(int orientation, AuthConstant.AuthEntityType entityType, List<String> entityIds) {
        if (ObjectUtil.isEmpty(entityIds)) return false;

        ICurrentTenant currentTenant = requestUtils.getCurrentTenant();
        TenantDetails tenantDetails = redisTransfer.getTenantDetails(currentTenant.getUsername());
        if (ObjectUtil.isEmpty(tenantDetails)) return false;

        List<AuthPayload> authPayloads = tenantDetails.getAuthPayloads();
        if (!ObjectUtil.isEmpty(authPayloads)) {
            for (AuthPayload authPayload : authPayloads) {
                Map<AuthConstant.AuthEntityType, List<AuthPayload.AuthEntity>>
                        authEntities = authPayload.getAuthEntities();
                if (ObjectUtil.isEmpty(authEntities)) continue;

                List<AuthPayload.AuthEntity> entities = authEntities.get(entityType);
                if (!ObjectUtil.isEmpty(entities)) {
                    List<AuthPayload.AuthEntity> handleEntities = new ArrayList<>(entityIds.size());
                    for (String entityId : entityIds) {
                        handleEntities.add(new AuthPayload.AuthEntity(entityId, entityType.getCode(),
                                entityType.getRemark()));
                    }
                    if (orientation == ADD) {
                        // 添加操作
                        entities.addAll(handleEntities);
                    } else {
                        // 移除操作
                        entities.removeAll(handleEntities);
                    }
                    break;
                }
            }
            return redisTransfer.setTenantDetails(currentTenant.getUsername(), tenantDetails);
        }
        return false;
    }
}
